using System;
using System.Globalization;
using System.Runtime.Serialization;

namespace Bookvar.ObjectModel.Actions.Collaboration
{
    [DataContract]
    [Serializable]
    public class ChangeTopicNameAction : ActionBase
    {
        private string newName;
        private Guid topicId;

        [DataMember]
        public string NewName
        {
            get { return newName; }
            set { newName = value; }
        }

        [DataMember]
        public Guid TopicId
        {
            get { return topicId; }
            set { topicId = value; }
        }

        public ChangeTopicNameAction()
        {
        }

        public ChangeTopicNameAction( Guid topicId, string newName )
        {
            if ( newName == null )
            {
                throw new ArgumentNullException( "newName" );
            }

            this.topicId = topicId;
            this.newName = newName;
        }

        public override void Execute( IExecutionContext context )
        {
            if ( context == null )
            {
                throw new ArgumentNullException( "context" );
            }
            if ( TopicId == Guid.Empty )
            {
                throw new InvalidOperationException( "TopicId is not properly set" );
            }

            try
            {
                context.ExecutionMode = ExecutionMode.Execution;
                Topic changedTopic = context.MainTopic.FindTopic( TopicId );
                if ( changedTopic != null )
                {
                    changedTopic.Name = NewName;
                }
            }
            finally
            {
                context.ExecutionMode = ExecutionMode.None;
            }
        }

        public override string ToString()
        {
            return string.Format(CultureInfo.CurrentCulture, "TopicId: {0}, NewName: {1}", TopicId, NewName );
        }
    }
}